<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="5">
          <a-descriptions-item label="单号"> {{ formState.lsh || '-' }}</a-descriptions-item>
          <a-descriptions-item label="盘点仓库">{{ formState.ckmc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="">{{ formState.zeroFlag === 1 ? '包含零库存项目' : '不包含零库存项目' || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单人"> {{ formState.createUser || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单日期">{{ formState.createTime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>

    <a-card class="mt-2 flex-1">
      <div class="absolute top-[-9999px] hidden">
        <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
        <PrintView id="printMe" :print-data="printData" />
        <a-button ref="preDiskPrintView" v-print="{ id: 'preDiskPrintView' }">打印</a-button>
        <PreDiskPrintView id="preDiskPrintView" :print-data="printData" />
      </div>
      <div class="flex justify-between mb-2">
        <a-form :model="searchForm" class="form-style-flex">
          <a-form-item name="zjm" label="" class="">
            <a-input v-model:value="searchForm.zjm" class="w-64" placeholder="药品编号/药品名称/助记码" @press-enter="getDetailData" />
          </a-form-item>
          <a-form-item name="merge" label="合并药品" class="ml-4">
            <a-switch v-model:checked="searchForm.merge" @change="getDetailData()" />
          </a-form-item>
        </a-form>
        <a-space>
          <a-button :disabled="formState.status !== 1" @click="onReset()"> 重置盘点数 </a-button>
          <a-button :disabled="formState.status !== 1" @click="onPrintFront"> 盘前打印 </a-button>
          <a-button @click="onPrint"> 盘点差异表 </a-button>
          <a-button v-if="formState.status === 1" type="primary" @click="onClickType(2)"> 盘点完毕 </a-button>
          <a-button v-else type="primary" @click="onClickQuash(1)"> 撤销完毕 </a-button>
        </a-space>
      </div>
      <BaseTable :data-source="dataSource" :column-code="searchForm.merge ? '000980' : '00001077'" :loading="loading" fill :extra-height="64">
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'mc'">
            <MedicineInfo :value="{ mc: record.mc, gg: record.gg, cj: record.cj }" />
          </template>
          <template v-if="column.dataIndex === 'checkSl' && formState.status === 1">
            <EditCell title="盘点数">
              <BaseInput
                v-model:value="record.checkSl"
                v-input:int
                v-input-selection
                placeholder="请输入"
                :auto-focus="focusCell.id === record.id"
                @keyup.enter="onKeyupSl(record)"
                @blur="onBlurSave(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'diffSl'">
            <div v-if="record.diffSl === 0">{{ record.diffSl }}</div>
            <div v-else-if="record.diffSl > 0" class="text-red-500">{{ record.diffSl }}</div>
            <div v-else-if="record.diffSl < 0" class="text-blue-700">{{ record.diffSl }}</div>
          </template>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
// import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import PrintView from './PrintView'
import PreDiskPrintView from './PreDiskPrintView'

const formState = ref({})
const loading = ref(false)
const dataSource = ref([])
const route = useRoute()
const router = useRouter()
const searchForm = ref({
  zjm: '',
  merge: false
})
const focusCell = ref({})
const printData = ref({})
const printMe = ref()
const preDiskPrintView = ref()
const getMainData = async () => {
  //获取盘点单总表列表
  const { data, code } = await post('/drugStorage/psiform/getInventoryHeadList', {
    dhmc: route.query?.lsh
  })
  if (code === 0) {
    formState.value = data[0]
  }
}
const onKeyupSl = (record) => {
  focusCell.value = findNextData(dataSource.value, record.id)
}
//盘点结束
const onClickType = async (status) => {
  if (dataSource.value.every((item) => item.checkSl !== '')) {
    const { msg, code } = await post('/drugStorage/psiform/doUpdateCheckStatus', { ...formState.value, status })
    if (code !== 0) return message.error(msg)
    message.success(msg)
    getMainData()
  } else {
    message.error('盘点数不可为空')
  }
}
//失焦保存
const onBlurSave = async (record) => {
  record.checkSl = record.checkSl ? record.checkSl : '0'
  const { msg, code } = await post('/drugStorage/psiform/doSaveInventoryDetail', record)
  if (code !== 0) return message.error(msg)
  record.diffSl = record.checkSl - record.storeSl
  message.success(msg)
}
//取消盘点
const onClickQuash = async (status) => {
  const { msg, code } = await post('/drugStorage/psiform/doRollbackCheck', { ...formState.value, status })
  if (code !== 0) return message.error(msg)
  getMainData()
  message.success(msg)
}
//重置盘点数
const onReset = async () => {
  const { msg, code } = await post('/drugStorage/psiform/doResetCheckData', { ...formState.value })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getDetailData()
}
//匹配id并返回下一条id
const findNextData = (array, targetId) => {
  const index = array.findIndex((item) => item.id === targetId)
  if (index !== -1 && index < array.length - 1) {
    return array[index + 1]
  } else {
    return getDetailData() // 如果找不到或者目标 id 已经是最后一个，则返回 null 或者其他自定义的值
  }
}
const getDetailData = async () => {
  //盘点明细
  loading.value = true
  const { data, code } = await post('/drugStorage/psiform/getInventoryDetailList', {
    lsh: route.query.lsh,
    zjm: searchForm.value.zjm,
    merge: searchForm.value.merge,
    pageSize: 999,
    pageNum: 1
  })
  loading.value = false
  if (code === 0) {
    // data.forEach((i) => {
    //   i.checkSl = i.storeSl
    // })
    dataSource.value = data
  }
}

// 盘点差异表打印
const onPrint = async () => {
  const { code, msg, data } = await post('/drugStorage/psiform/printKcStoreCheckCyList', { lsh: formState.value.lsh })
  if (code !== 0) return message.error(msg)

  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      setPrintSize('A4', 'landscape')
      preDiskPrintView.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

// 盘点前打印
const onPrintFront = async () => {
  const { code, msg, data } = await post('/drugStorage/psiform/printKcStoreCheckPqList', { lsh: formState.value.lsh })
  if (code !== 0) return message.error(msg)

  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      setPrintSize('A4', 'landscape')
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}
watch(
  () => route.query?.lsh,
  (val) => {
    if (val) {
      getMainData()
      getDetailData()
    }
  },
  {
    immediate: true
  }
)
// watchEffect(() => {
//   if (route.query?.lsh) {
//     getMainData()
//     getDetailData()
//   }
// })
</script>
<style lang="less" scoped>
:deep(.ant-card-head) {
  padding-left: 8px;
}
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
